import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import DBSCAN
import matplotlib.patches as patches
import pickle


# 从文件中读取之前保存的Matern簇数据
with open("matern_cluster_data.pkl", "rb") as f:
    points, parent_points_x, parent_points_y = pickle.load(f)
radius = 20  # 圆形区域半径
# 创建一个包含两个子图的窗口
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 8))

# 获取离坐标原点最近的两个点的距离，以此距离作为半径画圆（假设原代码中此逻辑不变，此处直接复用部分代码逻辑）
center = (0, 0)  # 圆形区域中心坐标，这里假设和之前保存数据时的设定一致
distances = np.sqrt((points[:, 0] - center[0]) ** 2 + (points[:, 1] - center[1]) ** 2)
sorted_indices = np.argsort(distances)
radius_w = distances[
    sorted_indices[1]
]  # 取第二个最近的距离作为半径（索引从0开始，所以取1）
circle1 = plt.Circle(center, radius_w, fill=False, color="black")
ax1.add_patch(circle1)
circle2 = plt.Circle(center, radius_w, fill=False, color="black")
ax2.add_patch(circle2)

# 找出圆内的点
in_circle = (points[:, 0] - center[0]) ** 2 + (
    points[:, 1] - center[1]
) ** 2 <= radius_w**2

# 在第一个子图中绘制模拟Matern簇过程的图形
ax1.scatter(points[:, 0], points[:, 1], label="All Points")
parent_points = np.array(
    [(parent_points_x[i], parent_points_y[i]) for i in range(len(parent_points_x))]
)
ax1.scatter(
    parent_points[:, 0],
    parent_points[:, 1],
    marker="^",
    s=50,
    c="green",
    label="Cluster Centers",
)
ax1.set_xlim(center[0] - radius, center[0] + radius)
ax1.set_ylim(center[1] - radius, center[1] + radius)
ax1.set_aspect("equal", adjustable="box")
ax1.set_title("Matern Cluster Process")
ax1.set_xlabel("X-axis")
ax1.set_ylabel("Y-axis")
ax1.legend()

# 剔除圆内的点，获取用于聚类的点
points_for_clustering = points[~in_circle]

# 使用DBSCAN进行聚类
dbscan = DBSCAN(eps=3.2, min_samples=5)  # 这里的参数可根据实际情况调整
clusters = dbscan.fit_predict(points_for_clustering)

# 提取不同簇的点和噪声点，注意要根据points_for_clustering的索引对应回原points的索引来处理
unique_clusters = np.unique(clusters)
cluster_sets = {cluster: [] for cluster in unique_clusters}
for i, cluster_label in enumerate(clusters):
    if cluster_label != -1:
        # 根据在points_for_clustering中的索引，找到在原points中的对应点
        index_in_original = np.where(~in_circle)[0][i]
        cluster_sets[cluster_label].append(points[index_in_original])
    else:
        # 噪声点同样要找到在原points中的对应索引
        noise_indices = np.where(clusters == -1)[0]
        noise_indices_in_original = np.where(~in_circle)[0][noise_indices]
        for idx in noise_indices_in_original:
            cluster_sets[-1].append(points[idx])

# 在第二个子图中绘制DBSCAN聚类后的图形
for cluster_label, cluster_points in cluster_sets.items():
    if cluster_label != -1:
        ax2.scatter(
            [p[0] for p in cluster_points],
            [p[1] for p in cluster_points],
            label=f"Cluster {cluster_label}",
        )
    else:
        ax2.scatter(
            [p[0] for p in cluster_points],
            [p[1] for p in cluster_points],
            label="Noise Points",
            marker="x",
            c="gray",
        )
parent_points = np.array(
    [(parent_points_x[i], parent_points_y[i]) for i in range(len(parent_points_x))]
)
"""
ax2.scatter(
    parent_points[:, 0],
    parent_points[:, 1],
    marker="^",
    s=50,
    c="green",
    label="Cluster Centers",
)
"""
ax2.set_xlim(center[0] - radius, center[0] + radius)
ax2.set_ylim(center[1] - radius, center[1] + radius)
ax2.set_aspect("equal", adjustable="box")
ax2.set_title("Matern Cluster Process with DBSCAN Clustering")
ax2.set_xlabel("X-axis")
ax2.set_ylabel("Y-axis")
# ax2.legend(loc="upper right", fontsize="small")

# 标注willie
ax1.scatter(0, 0, marker="+", s=100, c="r", label="Willie")
ax2.scatter(0, 0, marker="+", s=100, c="r", label="Willie")

# 新增逻辑，以0.5的概率在所有点位置放置黑色正方形
square_size = 0.5  # 正方形边长，可以根据需求调整大小
for point in points:
    if np.random.rand() < 0.2:  # 以0.5的概率决定是否绘制正方形
        # 为ax1创建矩形对象并添加
        rect1 = patches.Rectangle(
            (point[0] - square_size / 2, point[1] - square_size / 2),
            square_size,
            square_size,
            linewidth=1,
            edgecolor="black",
            facecolor="none",
        )
        ax1.add_patch(rect1)
        # 为ax2创建矩形对象并添加
        rect2 = patches.Rectangle(
            (point[0] - square_size / 2, point[1] - square_size / 2),
            square_size,
            square_size,
            linewidth=1,
            edgecolor="black",
            facecolor="none",
        )
        ax2.add_patch(rect2)

# 将圆内的点变红
ax1.scatter(points[in_circle, 0], points[in_circle, 1], c="red")
ax2.scatter(points[in_circle, 0], points[in_circle, 1], c="red")
# 为每个簇绘制圆（新添加的逻辑）
for cluster_label, cluster_points in cluster_sets.items():
    if cluster_label != -1:
        cluster_points = np.array(cluster_points)
        # 计算簇内点坐标的均值作为圆心
        center_x = np.mean(cluster_points[:, 0])
        center_y = np.mean(cluster_points[:, 1])
        center_tuple = (center_x, center_y)
        # 计算圆心到每个点的距离，找到最大值作为半径
        distances = np.sqrt(
            (cluster_points[:, 0] - center_x) ** 2
            + (cluster_points[:, 1] - center_y) ** 2
        )
        radius = np.max(distances)
        # 在两个子图中分别绘制圆
        circle1 = plt.Circle(center_tuple, radius, fill=False, color="blue")
        ax1.add_patch(circle1)
        circle2 = plt.Circle(center_tuple, radius, fill=False, color="blue")
        ax2.add_patch(circle2)
plt.show()
